package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Strings;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Component
@Slf4j
@Topic(TopicConfig.VMS_RESULT_TOPIC)
public class DealResultHandle implements MsgHandler {
    @Autowired
    VendoutRunningService vendoutRunningService;
    @Autowired
    ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VendoutResultContract vendoutResultContract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        if(Strings.isNullOrEmpty(vendoutResultContract.getInnerCode())) return;
        if (vendoutResultContract.isSuccess()) {
            QueryWrapper<VendoutRunningEntity> query = new QueryWrapper<>();
            VendoutRunningEntity one = vendoutRunningService.getOne(query.lambda()
                    .eq(VendoutRunningEntity::getOrderNo, vendoutResultContract.getVendoutData().getOrderNo()));
            one.setStatus(true);
            log.info("修改running表状态为true");
            vendoutRunningService.updateById(one);
        }else {
            //失败，回滚库存
            ChannelEntity channelInfo = channelService.getChannelInfo(vendoutResultContract.getInnerCode(), vendoutResultContract.getVendoutData().getChannelCode());
            channelInfo.setCurrentCapacity(channelInfo.getCurrentCapacity()+1);
            channelService.updateById(channelInfo);
        }
    }
}
